package cn.dapeng.linked;

/**
 * 使用单链表，实现队列
 */
public class MyQueue<V> {

    private Node<V> head, tail;

    private int size;

    public MyQueue() {
        head = null;
        tail = null;
        size = 0;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int getSize() {
        return size;
    }

    public void offer(V v) {
        Node cur = new Node(v);
        if (tail == null) {
            head = cur;
            tail = cur;
        } else {
            tail.next = cur;
            tail = cur;
        }
        size++;
    }

    public V peek() {
        if (head != null) {
            return head.value;
        }
        return null;
    }

    public V poll() {
        V v = null;
        if (head != null) {
            v = head.value;
            head = head.next;
            size--;
        }

        if (head == null) {
            tail = null;
        }
        return v;
    }

    public static class Node<V> {
        public V value;

        public Node<V> next;

        public Node(V v) {
            this.value = v;
        }
    }


    public static void main(String[] args) {
        MyQueue<Integer> myQueue = new MyQueue<>();

        for (int i = 0; i < 10; i++) {
            myQueue.offer(i);
        }
        System.out.println("size = " + myQueue.size);

        while (!myQueue.isEmpty()) {
            System.out.println(myQueue.poll());
        }

    }


}
